import { GreyOrColorWeakType } from '@/stores/types'

const useTheme = () => {
    const { config, setPropValue } = useConfigStore()
    const initTheme = () => {
        setPrimaryColor(config.primaryColor)
        setDark()
        if (config.isGrey) {
            setGreyOrColorWeak('isGrey', true)
        } else if (config.isColorWeak) {
            setGreyOrColorWeak('isColorWeak', true)
        }
    }
    onMounted(() => {
        colorLevelChange(config.primaryColor, config.isDark)
    })
    // 监听主题颜色和暗黑模式是否改变，设置主题色梯度数据
    watch(
        () => [config.isDark, config.primaryColor],
        () => {
            colorLevelChange(config.primaryColor, config.isDark)
        },
    )
    // 主题颜色设置
    const setPrimaryColor = (value: any) => {
        const el = document.documentElement
        // 获得 css 变量的值
        const currentPrimaryColor = getComputedStyle(el).getPropertyValue('--el-color-primary')
        if (config.primaryColor === value && currentPrimaryColor === value) return
        // 设置 css 变量
        el.style.setProperty('--el-color-primary', `${value}`)
        // 设置全局主题颜色
        setPropValue('primaryColor', value)
    }
    // 暗黑模式设置
    const setDark = () => {
        const html = document.documentElement
        html.className = config.isDark ? 'dark' : ''
        const isDark = html.className === 'dark' ? true : false
        setPropValue('isDark', isDark)
    }
    // 灰色模式和色弱模式切换
    const setGreyOrColorWeak = (type: GreyOrColorWeakType, value: boolean) => {
        const body = document.body as HTMLElement
        if (!value) return body.removeAttribute('style')
        const styles: Record<GreyOrColorWeakType, string> = {
            isGrey: 'filter: grayscale(1)',
            isColorWeak: 'filter: invert(80%)',
        }
        body.setAttribute('style', styles[type])
        const propName = type === 'isGrey' ? 'isColorWeak' : 'isGrey'
        setPropValue(propName, false)
    }
    // 设置主题色梯度数据
    const colorLevelChange = (value: string, isDark: boolean) => {
        // 颜色梯度数据
        const level: number[] = [3, 5, 7, 8, 9]
        if (isDark) {
            // 变浅主题颜色
            level.forEach((item: number) => {
                document.documentElement.style.setProperty(`--el-color-primary-light-${item}`, `${getDarkColor(value, item / 10)}`)
            })
            // 加深主题颜色
            document.documentElement.style.setProperty(`--el-color-primary-dark-2`, `${getLightColor(value, 2 / 10)}`)
        } else {
            // 变浅主题颜色
            level.forEach((item: number) => {
                document.documentElement.style.setProperty(`--el-color-primary-light-${item}`, `${getLightColor(value, item / 10)}`)
            })
            // 加深主题颜色
            document.documentElement.style.setProperty(`--el-color-primary-dark-2`, `${getDarkColor(value, 2 / 10)}`)
        }
    }
    return { initTheme, setPrimaryColor, setDark, setGreyOrColorWeak }
}
export default useTheme
